#include "Player.h"
#include "TiledMapInfo.h"
#include <math.h>
Player::Player(){
}

Player::~Player(){
}

Player* Player::m_player = NULL;

Player* Player::create(Node* node){
	if (m_player != NULL) return m_player;
	m_player = new Player();
	if (m_player && m_player->init(node)){
		m_player->autorelease();
		m_player->retain();
		return m_player;
	}
	else{
		CC_SAFE_DELETE(m_player);
	}
	return m_player;
}

void Player::delPlayer(){
	if (m_player != NULL){
		delete(m_player);
		m_player = NULL;
	}
	
}

bool Player::setTagPosition(float x, float y){
	this->getBox(x, y);
	for (auto dstPos : a){
		Vec2 tiledPos = TiledMapInfo::tileCoorForPosition(m_map, Vec2(dstPos.x, dstPos.y));

		int tiledGid = meta->getTileGIDAt(tiledPos);

		if (tiledGid != 0){
			Value properties = m_map->getPropertiesForGID(tiledGid);
			ValueMap propertiesMap = properties.asValueMap();

			if (propertiesMap.find("Collidable") != propertiesMap.end()){
				Value prop = propertiesMap.at("Collidable");
				if (prop.asString().compare("true") == 0){
					
					return false;
				}
			}
		}
	}
	this->setPosition(x, y);
	setViewPointByPlayer();
	return true;
}

void Player::setTagRotation(float rotation){
	this->setRotation(rotation);
	auto tank = (Tank*)m_node;
	tank->setHeadRotation(tank->getHeadRotation() + m_rotation - rotation);
	m_rotation = rotation;	
}

bool Player::init(Node* node){
	bool bRet = false;

	do{
		CC_BREAK_IF(!node);
		this->bindNode(node);
		bRet = true;
	} while (0);
	return true;
}

void Player::setViewPointByPlayer(){
	if (NULL == m_node){
		return;
	}

	TMXTiledMap* parent = (TMXTiledMap*)getParent();
	Size tileSize = m_map->getTileSize();
	Size mapTileNum = m_map->getMapSize();
	Size mapSize = Size(tileSize.width*mapTileNum.width, tileSize.height*mapTileNum.height);

	Size visibleSize = Director::getInstance()->getVisibleSize();

	Vec2 spritePos = this->getPosition();

	float x = std::max(spritePos.x, visibleSize.width / 2);
	float y = std::max(spritePos.y, visibleSize.height / 2);

	x = std::min(x, mapSize.width - visibleSize.width / 2);
	y = std::min(y, mapSize.height - visibleSize.height / 2);

	Vec2 destPos = Vec2(x, y);
	Vec2 centerPos = Vec2(visibleSize.width / 2, visibleSize.height / 2);

	Vec2 viewPos = centerPos - destPos;
	parent->setPosition(viewPos);
}

void Player::onDead(){
	m_controller->stop();
	NotificationCenter::getInstance()->postNotification("lose", NULL);
	CCLOG("onDead");
}

void Player::hurt(int val){
	if (m_isDead){
		return;
	}
	m_HP -= val;
	if (m_HP <= 0){
		m_isDead = true;
		this->onDead();
		m_HP = 0;
	}
}

